import { ProjectItem } from './../pr/reflection/ProjectItem'
import { addEventListener, eventBus, renderingTasks } from './index'
import { EventType } from './../../constants/event'

interface JobEvent {
  jobID: string
  data?: any
}

function handleJobCanceled(e: { data: JobEvent }) {
  console.log(e)
  const job = renderingTasks.get(e.data.jobID)
  if (job) {
    job.status = 'canceled'
    job.msg = e.data.data
    eventBus.emit(EventType.EncoderJobCanceled, job)
  }
}

function handleJobComplete(e: { data: JobEvent }) {
  console.log(e)
  const job = renderingTasks.get(e.data.jobID)
  if (job) {
    job.status = 'complete'
    job.outputFilePath = e.data.data
    eventBus.emit(EventType.EncoderJobComplete, job)
  }
}

function handleJobError(e: { data: JobEvent }) {
  console.log(e)
  const job = renderingTasks.get(e.data.jobID)
  if (job) {
    job.status = 'error'
    job.msg = e.data.data
    eventBus.emit(EventType.EncoderJobError, job)
  }
}

function handleJobProgress(e: { data: JobEvent }) {
  const job = renderingTasks.get(e.data.jobID)
  if (job) {
    job.status = 'progress'
    job.progress = parseFloat(e.data.data || '0')
    eventBus.emit(EventType.EncoderJobProgress, job)
  }
}

function handleJobQueued(e: { data: JobEvent }) {
  const job = renderingTasks.get(e.data.jobID)
  if (job) {
    job.status = 'queued'
    eventBus.emit(EventType.EncoderJobQueued, job)
  }
}

function handlePremiereItemAdded(e: { data: { project: string; item: any } }) {
  console.log(e)
  console.log(new ProjectItem(e.data.item))
  eventBus.emit(EventType.PremiereItemAdded, e)
}

function handlePremiereProjectChanged(e: {
  data: { project: string; item: any }
}) {
  console.log(e)
  eventBus.emit(EventType.PremiereProjectChanged, e)
}

function handleLog(e: { data: string }) {
  console.log(e.data)
}
function handleRenderProgress(e: {
  data: {
    id: number
    progress: number
  }
}) {
  eventBus.emit(EventType.RenderProgress, e.data)
}

function handleRenderComplete(e: {
  data: {
    id: number
    status: string
    filePath: string
  }
}) {
  console.log(e)
  if (e.data.status === 'Done!') {
    eventBus.emit(EventType.RenderComplete, e.data)
  } else {
    eventBus.emit(EventType.RenderFailed, e.data)
  }
}

addEventListener(EventType.EncoderJobCanceled, handleJobCanceled)
addEventListener(EventType.EncoderJobComplete, handleJobComplete)
addEventListener(EventType.EncoderJobError, handleJobError)
addEventListener(EventType.EncoderJobProgress, handleJobProgress)
addEventListener(EventType.EncoderJobQueued, handleJobQueued)
addEventListener(EventType.PremiereItemAdded, handlePremiereItemAdded)
addEventListener(EventType.PremiereProjectChanged, handlePremiereProjectChanged)
addEventListener(EventType.Log, handleLog)
addEventListener(EventType.RenderProgress, handleRenderProgress)
addEventListener(EventType.RenderComplete, handleRenderComplete)
